package cn.seocoo.platform.api.controller.pay;


import cn.seocoo.platform.common.config.pay.AlipayConfig;
import cn.seocoo.platform.common.pay.alipay.AliPayUtils;
import cn.seocoo.platform.common.utils.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @ClassName: MaterialController
 * @description: 支付宝回调
 * @author: wujian
 * @Date: 2019-10-21 16:16
 **/
@RestController
@RequestMapping("/api/pay")
public class AliPayNotifyController {


    private static final Logger logger = LoggerFactory.getLogger(AliPayUtils.class);



    /**
     * @return void
     * @Author WuJian
     * @Description //支付宝回调接口
     * @Date 15:01 2019/11/4
     * @Param [request, response]
     **/
    @PostMapping("/aliPayNotify")
    public String aliPayNotify(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        logger.warn("--------------------------------> 收到支付宝回调 开始<--------------------------------");
        // 获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i];
            }
            // 乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        try {
            // 调用SDK验证签名
            boolean signVerfied = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type);
            logger.info("sdk验证签名:" + signVerfied);
            if (signVerfied) {
                //验签成功
                // 按照支付结果异步通知中的描述，对支付结果中的业务内容进行1\2\3\4二次校验，校验成功后在response中返回success，校验失败返回failure
                String tradeStatus = params.get("trade_status");
                if ("TRADE_SUCCESS".equals(tradeStatus)) {
                    logger.info("交易状态----------->交易支付成功");
                }
                // 收款支付宝账号
                String sellerId = params.get("seller_id");
                logger.info("收款支付宝账号----------->" + sellerId);
                // 支付宝订单号
                String orderNumber = params.get("out_trade_no");
                //交易流水号
                String trade_no = params.get("trade_no");
                String totalAmount = params.get("total_amount");
                String payAmount = params.get("buyer_pay_amount");
                logger.info("交易流水号----------->" + trade_no);
                logger.info("支付请求的订单号----------->" + orderNumber);
                logger.info("订单金额(元)----------->" + totalAmount);
                logger.info("付款金额(元)----------->" + payAmount);
                logger.info("实收金额(元)----------->" + params.get("receipt_amount"));
                Map<String, Object> orderMsg = null;
                if (!StringUtils.isNull(params.get("passback_params")) && params.get("passback_params").trim().length() > 5) {
                    // 附加数据
                    String passback_params = URLDecoder.decode(params.get("passback_params"), "UTF-8");
                    logger.info("公用回传参数:" + passback_params);
                    Map<String, Object> jsonToMap = JSONObject.parseObject(passback_params);
                    orderMsg = (Map<String, Object>) jsonToMap.get("orderMsg");
                }
                //付款方userCode
                String userCode = orderMsg.get("userCode").toString();
                //订单类型->key 区分
                Object key = orderMsg.get("key");
                //------------------------------------------------------------->
                String type = null;
                String remark = null;
                //素材订单

                return "success";
            } else {
                // 验签失败则记录异常日志，并在response中返回failure.
                logger.warn("支付失败!验签失败！");
                return "failure";
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
            logger.error("支付失败!错误信息：" + e.getErrMsg());

        } catch (Exception e1) {
            e1.printStackTrace();
            logger.error("支付失败!出现错误：" + e1.getMessage());
        }
        return "failure";
    }


}
